<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */

namespace MoChat\App\Call\Action\Dashboard;

use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Call\Constants\ClientTypeCode;
use MoChat\App\Call\Logic\RecordIndexLogic;
use MoChat\App\Client\Model\Client;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Rbac\Middleware\PermissionMiddleware;
use MoChat\App\Client\Logic\IndexLogic;
use MoChat\App\Sales\Contract\CallRecordContract;
use MoChat\App\Sales\Contract\SalesClientTaskContract;
use MoChat\App\Sales\Model\CallRecord;
use Hyperf\Di\Annotation\Inject;
use MoChat\App\User\Model\User;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;

/**
 * 呼叫记录新版.
 * @Controller
 */
class RecordList extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var CallRecordContract
     */
    protected CallRecordContract $callRecordService;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     *
     * @RequestMapping(path="/dashboard/call/recordList", methods="GET")
     */
    public function handle(): \Hyperf\Contract\LengthAwarePaginatorInterface
    {
        $user = user();
        if (empty($user)) {
            throw new CommonException(ErrorCode::AUTH_UNAUTHORIZED, '登入异常请重新登入');
        }
        $data = $this->request->all();
        $this->validated($data);
        $list = Db::table('call_record as record')
            ->join('user as user', 'user.id', '=', 'record.user_id')
            ->leftJoin('work_employee as employee', 'employee.log_user_id', '=', 'user.id')
            ->leftJoin('client as client', 'client.id', '=', 'record.client_id')
            ->leftJoin('client_follow_record as follow', 'follow.client_id', '=', 'client.id')
            ->when(!empty($data['employeeId']), function ($query) use ($data) {
                $query->where('employee.id', '=', $data['employeeId']);
            })
            ->when(!empty($data['clientId']), function ($query) use ($data) {
                $query->where('client.id', '=', $data['clientId']);
            })
            ->when(!empty($data['clientType']), function ($query) use ($data) {
                $query->where('client.b2b_user_type', '=', $data['clientType']);
            })
            ->when(!empty($data['callStatus']), function ($query) use ($data) {
                //1:接通2未接通
                if ($data['callStatus'] == 1) {
                    $query->where('record.call_duration', '>', 0);
                }
                if ($data['callStatus'] == 2) {
                    $query->where('record.call_duration', '=', 0);
                }
            })
            ->when(!empty($data['callType']), function ($query) use ($data) {
                $query->where('record.call_type', '=', $data['callType']);
            })
            ->when(!empty($data['startTime']) && !empty($data['endTime']), function ($query) use ($data) {
                $query->whereBetween('record.created_time', [$data['startTime'], $data['endTime']]);
            })
            ->where('record.type','<>',2)
            ->select([
                'record.id',
                'employee.name',//员工
                'record.call_type as callType',//呼叫类型
                'user.extn',
                'client.enterprise_name as enterpriseName',//呼叫客户
                'client.b2b_user_type as b2bUserType',//客户等级
                Db::raw("'' as label"),//客户标签
                'record.created_time as createdTime',//呼叫时间
                'record.call_duration as callDuration',//通话时长
                Db::raw('SUBSTRING_INDEX(GROUP_CONCAT(mc_follow.remark ORDER BY mc_follow.id DESC SEPARATOR ","),",",1) AS remark'),//下次跟进内容
                Db::raw('SUBSTRING_INDEX(GROUP_CONCAT(mc_follow.followed_at ORDER BY mc_follow.id DESC SEPARATOR ","),",",1) AS followedAt'),//下次跟进时间
                Db::raw('SUBSTRING_INDEX(GROUP_CONCAT(mc_follow.returned_at ORDER BY mc_follow.id DESC SEPARATOR ","),",",1) AS returnedAt'),//下次面访时间
                'record.record_url as recordUrl',//语音
                'record.type',
            ])->groupBy([
                'record.id'
            ])->orderBy('record.id', 'desc')->paginate();
        if (!empty($list->items())) {
            foreach ($list->items() as &$datum) {
                $datum->callType = $datum->callType == 'in' ? '呼入' : '呼出';//呼叫类型
                $datum->b2bUserType = ClientTypeCode::getMessage($datum->b2bUserType);//客户等级
                $datum->callStatus = $datum->callDuration > 0 ? '接通' : '未接通';
                $datum->followedAt = $datum->followedAt ? $datum->followedAt : $datum->returnedAt;//下次跟进时间
                unset($datum->returnedAt);
            }
            unset($datum);
        }
        return $list;
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
            'page' => 'integer',
            'perPage' => 'integer',
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
            'page.integer' => '页码必须为整数',
            'perPage.integer' => '页码必须为整数',
        ];
    }
}
